package biz.core.controller;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.QueryWrapperFilter;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;
import org.wltea.analyzer.lucene.IKQueryParser;

import biz.core.base.BaseAction;
import biz.core.domain.Auction;
import biz.core.service.AuctionService;

import common.util.PinyinUtil;


public class AuctionAction extends BaseAction{
	private static final File indexDir=new File("D:\\luceneIndex");
	private AuctionService auctionService;
	private List<Auction> auctions=new LinkedList<Auction>();
	private String queryName="";
	private String isQuery="0";
	private String queryFiled="pinYinName";
	//private static Analyzer analyzer = new PaodingAnalyzer();
	private static Analyzer analyzer = new IKAnalyzer();
	
	private long searchResults;
	
	private double useTime;
	
	public long getSearchResults() {
		return searchResults;
	}

	public void setSearchResults(long searchResults) {
		this.searchResults = searchResults;
	}

	public double getUseTime() {
		return useTime;
	}

	public void setUseTime(double useTime) {
		this.useTime = useTime;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String execute() throws Exception {
		long startTime = System.currentTimeMillis();
	    if("1".equals(isQuery)){
	    	System.err.println(queryName);
	    	//true为包含汉字
	    	boolean isHasHanzi=Pattern.compile("[\u4E00-\u9FA5]").matcher(queryName).find();
//	    	if(isHasHanzi){
//	    		queryFiled="name";
//	    	}
	    	IndexSearcher searcher = new IndexSearcher(FSDirectory.open(indexDir));
	    	//Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31);
	    	//paoding
	    	/*ArrayList dicList = new ArrayList();
	        dicList.add("的");
	        dicList.add("的商");
	        Dictionary.loadExtendStopWords(dicList);*/
	    	Query query = IKQueryParser.parse(queryFiled, queryName);
	    	//Query query=parser.parse(queryName);
	    	IKQueryParser.setMaxWordLength(true);
	    	QueryWrapperFilter filter = new QueryWrapperFilter(query);
	    	TopDocs results = searcher.search(query,filter,50000);
			ScoreDoc[] hits = results.scoreDocs;
			for (ScoreDoc scoreDoc : hits) {
				Document doc=searcher.doc(scoreDoc.doc);
				Auction auction=new Auction();
				auction.setId(Long.valueOf(doc.get("id")));
				auction.setName(doc.get("name"));
				auction.setPinYinName(doc.get("pinYinName"));
				auction.setRemarks(doc.get("remarks"));
				auctions.add(auction);
			}
			this.searchResults = hits.length;
			this.useTime = (System.currentTimeMillis()-startTime)*1.00000/1000;
//			DecimalFormat df=new DecimalFormat("#.####");
//			String useStr = df.format(this.useTime);
//			this.useTime = Float.parseFloat(useStr);
//	    	//this.auctions=auctionService.findByName(queryName);
	    }
		return 	SUCCESS;
	}
	
	public String createIndex()throws Exception{
		try{
		List<Auction> allAuction=auctionService.findAll();
		Directory dir = FSDirectory.open(indexDir);
		//添加索引
		//doCreate(allAuction);
		doCreatePinYin(allAuction);
		}catch(IOException ioe){
			ioe.printStackTrace();
		}catch(Exception e){
	       e.printStackTrace();
	      }
		return SUCCESS;
	}
	
	public static void doCreate(List<Auction> auctions) throws IOException{
		Directory dir = FSDirectory.open(indexDir);
		//Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31);
		//paoding
		IndexWriterConfig iwc=new IndexWriterConfig(Version.LUCENE_31, analyzer);
		IndexWriter writer = new IndexWriter(dir, iwc);
		for (Auction auction : auctions) {
			Document doc=new Document();
			doc.add(new Field("id",auction.getId()+"", Field.Store.YES, Field.Index.ANALYZED_NO_NORMS));
			doc.add(new Field("name",auction.getName(), Field.Store.YES, Field.Index.ANALYZED_NO_NORMS));
			doc.add(new Field("remarks",auction.getRemarks()==null?"":auction.getRemarks(), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
			writer.addDocument(doc);
		}	
		writer.optimize();
        writer.close();
		
	}
	public static void doCreatePinYin(List<Auction> auctions) throws IOException{
		Directory dir = FSDirectory.open(indexDir);
		//Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31);
		//paoding
		IndexWriterConfig iwc=new IndexWriterConfig(Version.LUCENE_31, analyzer);
		IndexWriter writer = new IndexWriter(dir, iwc);
		for (Auction auction : auctions) {
			Document doc=new Document();
			String name=auction.getName();
//
			StringReader reader=new StringReader(name);
			
			StringBuilder builder=new StringBuilder();
			builder.append(PinyinUtil.stringArrayToString(PinyinUtil.getHeadByString(name)))
			.append(",").append(PinyinUtil.stringArrayToString(PinyinUtil.getHeadByString2(name)));
			
//			ArrayList dicList = new ArrayList();
//	        dicList.add("的");
//	        dicList.add("的商");
//	        Dictionary.loadExtendStopWords(dicList);
			TokenStream ts = analyzer.tokenStream("", reader);
			ts.reset();
			CharTermAttribute termAtt = ts
					.addAttribute(CharTermAttribute.class);
			while (ts.incrementToken()) {
				char[] fenci=termAtt.buffer();
				System.err.println(String.valueOf(fenci));
				builder.append(",").append(PinyinUtil.getHeadAllByString(String.valueOf(fenci),true,","));
				//.append(",").append(PinyinUtil.hanziToPinyinAll(fenci,","));
			}
	//		
			String pinYinName=builder.toString();
			doc.add(new Field("id",auction.getId()+"", Field.Store.YES, Field.Index.ANALYZED_NO_NORMS));
			doc.add(new Field("pinYinName",pinYinName, Field.Store.YES,Field.Index.ANALYZED_NO_NORMS));
			doc.add(new Field("name",name, Field.Store.YES, Field.Index.ANALYZED_NO_NORMS));
			doc.add(new Field("remarks",auction.getRemarks()==null?"":auction.getRemarks(), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
			writer.addDocument(doc);
		}	
		writer.optimize();
        writer.close();
		
	}
	
	
	public String updateIndex()throws Exception{
		try{
		List<Auction> allAuction=auctionService.findAll();
		Directory dir = FSDirectory.open(indexDir);
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31);
		IndexWriterConfig iwc=new IndexWriterConfig(Version.LUCENE_31, analyzer);
		IndexWriter writer = new IndexWriter(dir, iwc);
		for (Auction auction : allAuction) {
			Document doc=new Document();
			doc.add(new Field("id",auction.getId()+"", Field.Store.YES,Field.Index.ANALYZED_NO_NORMS));
			doc.add(new Field("name",auction.getName(), Field.Store.YES,Field.Index.ANALYZED_NO_NORMS));
			doc.add(new Field("remarks",auction.getRemarks()==null?"":auction.getRemarks(), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
			//writer.addDocument(doc);
			writer.updateDocument(new Term("id",auction.getId()+""), doc);
		}	
		writer.optimize();
        writer.close();
		}catch(IOException ioe){
			ioe.printStackTrace();
		}catch(Exception e){
	       e.printStackTrace();
	      }
		return SUCCESS;
	}
	
	public void setAuctionService(AuctionService auctionService) {
		this.auctionService = auctionService;
	}
	public void setAuctions(List<Auction> auctions) {
		this.auctions = auctions;
	}
	public List<Auction> getAuctions() {
		return auctions;
	}
	public String getIsQuery() {
		return isQuery;
	}
	public void setIsQuery(String isQuery) {
		this.isQuery = isQuery;
	}
	public AuctionService getAuctionService() {
		return auctionService;
	}
	public String getQueryName() {
		return queryName;
	}
	public void setQueryName(String queryName) {
		this.queryName = queryName;
	}
	
	public static void main(String[] args) throws Exception{
		long startTime = System.currentTimeMillis();
		String isQuery = "1";
		String queryName = "kn";
		String queryFiled="pinYinName";
	    if("1".equals(isQuery)){
	    	System.err.println(queryName);
	    	//true为包含汉字
	    	boolean isHasHanzi=Pattern.compile("[\u4E00-\u9FA5]").matcher(queryName).find();
//	    	if(isHasHanzi){
//	    		queryFiled="name";
//	    	}
	    	IndexSearcher searcher = new IndexSearcher(FSDirectory.open(indexDir));
	    	//Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31);
	    	//paoding
	    	/*ArrayList dicList = new ArrayList();
	        dicList.add("的");
	        dicList.add("的商");
	        Dictionary.loadExtendStopWords(dicList);*/
	    	Query query = IKQueryParser.parse(queryFiled, queryName);
	    	//Query query=parser.parse(queryName);
	    	IKQueryParser.setMaxWordLength(true);
	    	QueryWrapperFilter filter = new QueryWrapperFilter(query);
	    	TopDocs results = searcher.search(query,filter,500000);
			ScoreDoc[] hits = results.scoreDocs;
			List<Auction> auctions=new LinkedList<Auction>();
			for (ScoreDoc scoreDoc : hits) {
				Document doc=searcher.doc(scoreDoc.doc);
				Auction auction=new Auction();
				auction.setId(Long.valueOf(doc.get("id")));
				auction.setName(doc.get("name"));
				auction.setPinYinName(doc.get("pinYinName"));
				auction.setRemarks(doc.get("remarks"));
				auctions.add(auction);
			}
			long searchResults = hits.length;
			double useTime = (System.currentTimeMillis()-startTime)*1.0000/1000;
//			DecimalFormat df=new DecimalFormat("#.####");
//			String useStr = df.format(this.useTime);
//			this.useTime = Float.parseFloat(useStr);
//	    	//this.auctions=auctionService.findByName(queryName);			
			for(Auction auction : auctions){
				System.out.println(auction.getId());
				System.out.println(auction.getName());
				System.out.println(auction.getPinYinName());
				System.out.println(auction.getRemarks());				
			}
			System.out.println("共搜索出"+searchResults+"条数据,用时"+useTime+"秒");
	    }
	}
	
	

}
